#include "rel.h"

/**
 * parses a received data message
 *
 */ 
 
int parseDataMessage(){
  // Check against current sequence number
  // If matches, then write the file.  Ack back with correct 
  // ACK number
  // If frag byte is set, then create ack message with next
  // sequence number and send
  // If frab byte is not set, then create FSM2 message and send
  // If no match, then create ACK with sequence number of next packet
  // we expect to get and send ACK
  
  void * ptr = (void * ) &receiveMessageBuffer[1];
  unsigned long long * longPtr = (unsigned long long * ) ptr;
  unsigned long long receivedSequenceNumber = ntohll(*longPtr);
  
  if (debug){
  	puts("HELLO SHAR.  PUT braces .");
  }
  
  if (currentSequenceNumber == receivedSequenceNumber)
  {
    if(debug)
      printf("Current Seq #: %lld\nReceived Seq #: %lld\n", currentSequenceNumber, receivedSequenceNumber);
    
    int bufferSize = 0;
  
    bufferSize = receiveMessageBuffer[10] * 127; //calculate buffer size
    bufferSize = receiveMessageBuffer[11] + bufferSize;
 
    file_write(&receiveMessageBuffer[12], bufferSize); // write to file
    currentSequenceNumber++; //increment sequence number
    
    if(receiveMessageBuffer[9] == 0x00)
      {
      	pthread_mutex_lock(&mutexLock);
      	
        fileStatusCreation(2);
        file_close(0); //close file after last segment successfully received
        
        pthread_mutex_unlock(&mutexLock);
      }
    if(receiveMessageBuffer[9] == 0x01)
      createAckMessage(currentSequenceNumber);
  }
  else
  {
  if (debug){
  	puts("HELLO SHAR.  HAVE braces .");
  }
    createAckMessage(currentSequenceNumber);
  }
}

// create File Status Message
int createDataMessage() {
	
  pthread_mutex_lock ( &mutexLock );

  int i;
  int fileSize = 0;
  sendMessageBuffer[0] = 0xDD;

  //append sequence number
  void * ptr = (void * ) &sendMessageBuffer[1];
  unsigned long long * longPtr = (unsigned long long * ) ptr;
  *longPtr = htonll(currentSequenceNumber); 
    
  fileSize = file_read(fileName);

  if (fileSize >= 0)
  {
  	if(debug) 
  	  puts("I'm over here4");
    if (endOfFile)
        sendMessageBuffer[9] = 0x00;
    else {
    		if(debug)
    		  puts("More to frag");
        sendMessageBuffer[9] = 0x01;
    }
  }
  else
    return 0;
    
  sendMessageBuffer[10] = fileSize / 127;
  sendMessageBuffer[11] = fileSize % 127;
  if(debug){
	  puts("This is the send message buffer:");
 
  	printMessage(sendMessageBuffer, fileSize+12);
  }
  
  pthread_mutex_unlock ( &mutexLock );

  sendMessageSize = fileSize+12;
}
 
